package common;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by cc
 * Description:
 * User: CZH
 * Date: 2023-01-05
 * Time: 22:40
 */
public class DBUtil {
    // 需要封装和数据库之间的连接操作
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/oj_database?characterEncoding=utf8&useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";

    // 设计成单例模式的效果 - 懒汉模式(线程安全)
    private static volatile DataSource dataSource = null;
    private static DataSource getDataSource() {
        // 双重判定。
        if (dataSource == null) {
            // 第一次创建 mysqlDataSource 对象赋值的时候，需要保证线程安全，所以加锁
            synchronized (DBUtil.class) {
                // 如果为空，新建对象赋值数据
                if (dataSource == null) {
                    MysqlDataSource mysqlDataSource = new MysqlDataSource();
                    mysqlDataSource.setURL(URL);
                    mysqlDataSource.setUser(USERNAME);
                    mysqlDataSource.setPassword(PASSWORD);
                    dataSource = mysqlDataSource;
                }
            }
        }
        return dataSource;
    }

    // 提供方法获取连接
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    // 关闭释放连接的操作
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
